package com.kun.portal.webframe.util;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by Administrator on 2018/6/12.
 */
@ServerEndpoint("/message/{protocol}")
public class MessageBuss {
    private  static  CopyOnWriteArraySet< MessageBuss> sessions =  new CopyOnWriteArraySet<MessageBuss>();
    private  static ObjectMapper mapper = new ObjectMapper();
    private String  protocol;

    @OnOpen
    public void onOpen(Session session,@PathParam("protocol") String protocol , EndpointConfig conf ){
        this.protocol = protocol;
        this.session = session;
        System.out.println(conf.getUserProperties());
         Map <String,Object> map=conf.getUserProperties();
        sessions.add(this);

    }
    @OnClose
    public void onClose(Session session){
        sessions.remove(this);
    }

    @OnError
    public void onError(Session session, Throwable error){
         error.printStackTrace();
    }
    private  Session session;

    @OnMessage
    public void oneMessage(Session session,String msg){
            System.out.println(msg);
    }
    public static void sendMessage(Object object,String protocol) {

        String jackSon =null;
        try {
             jackSon = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        try {
            if (sessions.size() != 0) {
                for (MessageBuss s : sessions) {
                    if (s != null&&s.protocol.equals(protocol)) {
                        s.session.getBasicRemote().sendText(jackSon);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
